package com.tanhua.dubbo.api;


import cn.hutool.core.collection.CollUtil;
import com.tanhua.model.mongo.UserLocation;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Circle;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.Metrics;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.geo.GeoJsonPoint;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;

/**
 * @author Administrator
 */
@DubboService
public class UserLocationApiImpl implements UserLocationApi {
       @Autowired
       private MongoTemplate mongoTemplate;
    @Override
    public boolean updateLocation(Long userId, Double longitude, Double latitude, String address) {
        try {
            Query query = Query.query(Criteria.where("userId").is(userId));
            UserLocation userLocation = mongoTemplate.findOne(query, UserLocation.class);
            if (userLocation==null){
                UserLocation userLocations = new UserLocation();
                userLocations.setUserId(userId);
                userLocations.setUpdated(System.currentTimeMillis());
                userLocations.setCreated(System.currentTimeMillis());
                userLocations.setLastUpdated(System.currentTimeMillis());
                userLocations.setAddress(address);
                userLocations.setLocation(new GeoJsonPoint(latitude,longitude));
                mongoTemplate.save(userLocations);
            }else {
                Update update = Update.update("location",new GeoJsonPoint(latitude,longitude)).set("updated",System.currentTimeMillis())
                        .set("lastUpdated",userLocation.getLastUpdated());
                mongoTemplate.updateFirst(query,update,UserLocation.class);
            }
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public List<Long> queryNearUser(Long userId, Double valueOf) {
        Query query = Query.query(Criteria.where("userId").is(userId));
        UserLocation userLocation = mongoTemplate.findOne(query, UserLocation.class);
        if (userLocation==null){
            return null;
        }
        GeoJsonPoint geoJsonPoint = userLocation.getLocation();
        Distance distance = new Distance(valueOf/1000, Metrics.KILOMETERS);
        Circle circle = new Circle(geoJsonPoint,distance);
        Query query1 = Query.query(Criteria.where("location").withinSphere(circle));
        List<UserLocation> userLocations = mongoTemplate.find(query1, UserLocation.class);
        List<Long> userIds = CollUtil.getFieldValues(userLocations, "userId", Long.class);
        return userIds;
    }
}